import { ref, type Ref } from 'vue'
import { useAPIService } from './api'
import { useSSE, type SSEEventHandler } from './sse'
import type { 
  ChatCompletionRequest, 
  SSEEvent, 
  ChatMessage, 
  Task, 
  ExecutionStatus 
} from '@/types'

// 问答会话状态
export interface ChatSession {
  id: string
  isStreaming: boolean
  currentMessage: string
  tasks: Task[]
  executionStatus: ExecutionStatus | null
  error: string | null
}

// 问答服务类
export class ChatService {
  private apiService = useAPIService()
  private sse = useSSE()
  private sessions = new Map<string, ChatSession>()
  private currentSessionId: string | null = null

  constructor() {
    this.setupSSEHandlers()
  }

  /**
   * 设置SSE事件处理器
   */
  private setupSSEHandlers(): void {
    // 处理聊天内容流
    this.sse.on('chat.completion.chunk', (event: SSEEvent) => {
      const content = event.choices?.[0]?.delta?.content
      if (content && this.currentSessionId) {
        const session = this.sessions.get(this.currentSessionId)
        if (session && session.isStreaming) {
          session.currentMessage += content
        }
      }
    })

    // 处理任务链信息
    this.sse.on('tasks.custom.chunk', (event: SSEEvent) => {
      if (event.custom?.tasks && this.currentSessionId) {
        const session = this.sessions.get(this.currentSessionId)
        if (session) {
          session.tasks = event.custom.tasks
        }
      }
    })

    // 处理任务执行状态
    this.sse.on('task_run.custom.chunk', (event: SSEEvent) => {
      if (event.custom && this.currentSessionId) {
        const session = this.sessions.get(this.currentSessionId)
        if (session) {
          session.executionStatus = event.custom as ExecutionStatus
        }
      }
    })

    // 处理完成事件
    this.sse.on('chat.completion', (event: SSEEvent) => {
      if (this.currentSessionId) {
        const session = this.sessions.get(this.currentSessionId)
        if (session) {
          session.isStreaming = false
        }
      }
    })

    // 处理错误事件
    this.sse.on('error.custom.chunk', (event: SSEEvent) => {
      if (event.custom?.error && this.currentSessionId) {
        const session = this.sessions.get(this.currentSessionId)
        if (session) {
          session.error = event.custom.error.message || '未知错误'
          session.isStreaming = false
        }
      }
    })
  }

  /**
   * 开始新的聊天会话
   */
  async startChat(
    messages: Array<{ role: 'user' | 'assistant' | 'system'; content: string }>,
    sessionId?: string,
    options?: ChatCompletionRequest['custom']
  ): Promise<string> {
    // 生成或使用提供的会话ID
    const chatSessionId = sessionId || this.generateSessionId()
    
    // 初始化会话状态
    const session: ChatSession = {
      id: chatSessionId,
      isStreaming: true,
      currentMessage: '',
      tasks: [],
      executionStatus: null,
      error: null
    }
    
    this.sessions.set(chatSessionId, session)
    this.currentSessionId = chatSessionId

    try {
      // 连接SSE（如果尚未连接）
      if (!this.sse.isConnected()) {
        const sseUrl = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'}/chat/stream`
        await this.sse.connect(sseUrl)
      }

      // 构建请求
      const request: ChatCompletionRequest = {
        messages,
        stream: true,
        session_id: chatSessionId,
        custom: {
          priority: 'normal',
          language: 'zh-CN',
          include_reasoning: true,
          max_task_count: 10,
          execution_mode: 'auto',
          timeout: 300,
          ...options
        }
      }

      // 发送请求
      await this.apiService.chatCompletions(request)
      
      return chatSessionId

    } catch (error) {
      session.error = error instanceof Error ? error.message : '发送请求失败'
      session.isStreaming = false
      throw error
    }
  }

  /**
   * 获取会话信息
   */
  getSession(sessionId: string): ChatSession | null {
    return this.sessions.get(sessionId) || null
  }

  /**
   * 获取当前会话
   */
  getCurrentSession(): ChatSession | null {
    return this.currentSessionId ? this.getSession(this.currentSessionId) : null
  }

  /**
   * 停止当前会话的流式输出
   */
  stopStreaming(sessionId?: string): void {
    const targetSessionId = sessionId || this.currentSessionId
    if (targetSessionId) {
      const session = this.sessions.get(targetSessionId)
      if (session) {
        session.isStreaming = false
      }
    }
  }

  /**
   * 清除会话
   */
  clearSession(sessionId: string): void {
    this.sessions.delete(sessionId)
    if (this.currentSessionId === sessionId) {
      this.currentSessionId = null
    }
  }

  /**
   * 清除所有会话
   */
  clearAllSessions(): void {
    this.sessions.clear()
    this.currentSessionId = null
  }

  /**
   * 确认任务执行
   */
  async confirmTaskExecution(sessionId: string): Promise<void> {
    try {
      await this.apiService.confirmTaskExecution(sessionId)
    } catch (error) {
      const session = this.sessions.get(sessionId)
      if (session) {
        session.error = error instanceof Error ? error.message : '确认执行失败'
      }
      throw error
    }
  }

  /**
   * 修改任务
   */
  async modifyTasks(sessionId: string, modification: any): Promise<void> {
    try {
      const updatedTasks = await this.apiService.modifyTasks(sessionId, modification)
      const session = this.sessions.get(sessionId)
      if (session) {
        session.tasks = updatedTasks
      }
    } catch (error) {
      const session = this.sessions.get(sessionId)
      if (session) {
        session.error = error instanceof Error ? error.message : '修改任务失败'
      }
      throw error
    }
  }

  /**
   * 取消任务执行
   */
  async cancelExecution(sessionId: string): Promise<void> {
    try {
      await this.apiService.cancelTaskExecution(sessionId)
      const session = this.sessions.get(sessionId)
      if (session) {
        session.isStreaming = false
        session.executionStatus = null
      }
    } catch (error) {
      throw error
    }
  }

  /**
   * 暂停任务执行
   */
  async pauseExecution(sessionId: string): Promise<void> {
    try {
      await this.apiService.pauseTaskExecution(sessionId)
    } catch (error) {
      throw error
    }
  }

  /**
   * 恢复任务执行
   */
  async resumeExecution(sessionId: string): Promise<void> {
    try {
      await this.apiService.resumeTaskExecution(sessionId)
    } catch (error) {
      throw error
    }
  }

  /**
   * 注册自定义SSE事件处理器
   */
  onSSEEvent(objectType: Parameters<typeof this.sse.on>[0], handler: SSEEventHandler): void {
    this.sse.on(objectType, handler)
  }

  /**
   * 移除SSE事件处理器
   */
  offSSEEvent(objectType: Parameters<typeof this.sse.off>[0], handler: SSEEventHandler): void {
    this.sse.off(objectType, handler)
  }

  /**
   * 获取SSE连接状态
   */
  getSSEState() {
    return this.sse.getState()
  }

  /**
   * 断开SSE连接
   */
  disconnect(): void {
    this.sse.disconnect()
  }

  /**
   * 生成会话ID
   */
  private generateSessionId(): string {
    return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }
}

// 单例实例
const chatService = new ChatService()

// 组合式API
export const useChatService = () => {
  return chatService
}

// 响应式会话状态Hook
export const useChatSession = (sessionId?: Ref<string | null>) => {
  const session = ref<ChatSession | null>(null)
  const isStreaming = ref(false)
  const currentMessage = ref('')
  const tasks = ref<Task[]>([])
  const executionStatus = ref<ExecutionStatus | null>(null)
  const error = ref<string | null>(null)

  // 监听会话变化
  const updateSession = () => {
    const currentSessionId = sessionId?.value || chatService.getCurrentSession()?.id
    if (currentSessionId) {
      const chatSession = chatService.getSession(currentSessionId)
      if (chatSession) {
        session.value = chatSession
        isStreaming.value = chatSession.isStreaming
        currentMessage.value = chatSession.currentMessage
        tasks.value = chatSession.tasks
        executionStatus.value = chatSession.executionStatus
        error.value = chatSession.error
      }
    }
  }

  // 定期更新会话状态
  let updateInterval: number | null = null
  
  const startWatching = () => {
    updateInterval = window.setInterval(updateSession, 100)
  }

  const stopWatching = () => {
    if (updateInterval) {
      clearInterval(updateInterval)
      updateInterval = null
    }
  }

  // 开始监听
  startWatching()

  return {
    session,
    isStreaming,
    currentMessage,
    tasks,
    executionStatus,
    error,
    updateSession,
    startWatching,
    stopWatching
  }
}

export default chatService